import router, { constantRoutes } from "@/router"
import NProgress from "nprogress"
import "nprogress/nprogress.css"
import { getToken } from "@/utils/auth"
import store from "@/store"
import { Message } from "element-ui";

NProgress.configure({ showSpinner: false })
const whiteList = ["/login"]

router.beforeEach(async (to, from, next) => {
  if (getToken()) {
    if (to.path === '/login') {
      next()
      NProgress.done()
    } else {
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      console.log('hasRoles', hasRoles)
      if (hasRoles) {
        next()
      } else {
        const userInfo = JSON.parse(sessionStorage.getItem('userInfo')) || store.getters.userInfo
        console.log('store.getters.userInfo', userInfo)
        if (userInfo) {
          try {
            const { role } = await store.dispatch('user/getUserInfo', userInfo)
            console.log('roles', role)
            const accessRoutes = await store.dispatch('permission/generateRoutes', [role])
            router.options.routes = constantRoutes.concat(accessRoutes)
            router.addRoutes(accessRoutes)
            next({ ...to, replace: true })
          } catch (error) {
            Message.error(error || 'Has Error')
            next(`/login`)
            NProgress.done()
          }
        } else {
          next()
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next({ path: "/login" }) // 否则全部重定向到首页
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
